package com.network.config;

import com.network.handler.LoginErrorHandler;
import com.network.handler.LoginSuccessHandler;
import com.network.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author peng
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(customUserDetailsService);
        //remember me
        auth.eraseCredentials(false);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .loginPage("/login")        // 设置登录页面
                .successHandler(loginSuccessHandler()) //登录成功操作
                .failureHandler(loginErrorHandler()) //登录失败
                .loginProcessingUrl("/login")  // 自定义的登录接口
                .and()
                .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login","/static/**", "/login.html","/checkcode").permitAll()     // 设置所有人都可以访问登录页面
                .antMatchers("/add/**").hasRole("addRole") //添加必须有有添加角色才可以进行添加操作
                .antMatchers("/put/**").hasRole("putRole")//更新必须有更新角色才可以更新
                .antMatchers("/delete/**").hasRole("delRole") //删除开头的请求 必须有删除权限才可以删除
                .anyRequest()               // 任何请求,登录后可以访问
                .authenticated()
                .and()
                .csrf().disable();          // 关闭csrf防护

        //a frame because it set 'X-Frame-Options' to 'deny'. 解决
        http.headers().frameOptions().sameOrigin();

        http.sessionManagement().invalidSessionUrl("/login");


    }

    @Bean
    public LoginSuccessHandler loginSuccessHandler(){
        return new LoginSuccessHandler();
    }

    @Bean
    public LoginErrorHandler loginErrorHandler()
    {
       return new LoginErrorHandler();
    }


}
